var config = require('../../../../config')
module.exports = class extends think.Controller {
  async indexAction () {
    var data = this.post()
    var db = this.mongoose('mongoose/timeout')
    const loglist = this.mongoose('mongoose/loglist');
    console.log('===========================================')
    await new loglist({
      level: 'Info',
      name: '收到消息',
      type: '服务端',
      result: data
    }).save()
    var global_user = this.model( 'user' ).getuser()
    var timeout_list = this.model('user').getTimeoutList()
    if ( global_user.state > 0 ) {
      global_user = global_user.data
    } else {
      global_user = {}
    }
    if ( typeof ( data ) == 'string' ) {
      try {
        data = JSON.parse( data );
      } catch ( e ) {
        res.json( { "status": -2, "msg": "JSON格式错误" } );
      }
    }
    console.log('组长账号是否存在', data.pid in global_user)
    console.log('组长是否等于客服', data.pid == data.cs_id)
    console.log('组长账号', global_user[data.pid])
    if ( !( data.pid in global_user ) ) {
      console.log( '对应主账户不在线' );
      await new loglist({
        level: 'Info',
        name: '消息转发组长',
        type: '服务端',
        result: {
          data: data,
          msg: '组长找好不在线'
        }
      }).save()
    } else {
      if ( data.pid !== data.cs_id ) {
        let sendType = []
        think.global.loginType.forEach(( item ) => {
          console.log( '同步发送给主账户' );
          if ( item in global_user[data.pid] ) {
            sendType.push(item)
            var redata = JSON.parse(JSON.stringify(data))
            redata.cs_id = redata.pid
            if (this.model('socket').getSocket(data.pid, item)) {
              this.model('socket').getSocket(data.pid, item).emit('sendMsg', redata)
            } else {
              global_user[data.pid][item].socket.emit( 'sendMsg', redata )
            }
          }
        });
        await new loglist({
          level: 'Info',
          name: '消息转发组长',
          type: '服务端',
          result: {
            data: data,
            sendType: sendType
          }
        }).save()
      }
    }
    var sendType = [];
    if ( data.cs_id in global_user ) {
      think.global.loginType.forEach(( item ) => {
        console.log( '同步发送给客服', item )
        if ( item in global_user[data.cs_id] ) {
          sendType.push( item );
          if (this.model('socket').getSocket(data.cs_id, item)) {
            this.model('socket').getSocket(data.cs_id, item).emit('sendMsg', data)
          } else {
            global_user[data.cs_id][item].socket.emit( 'sendMsg', data )
          }
        }
      } );

      if (parseInt(data.send_type) === 1001) {
        if (data.openid in timeout_list) {
          clearTimeout(timeout_list[data.openid])
          console.log('客户连续发送消息，重置计时器！')
        }
        try {
          var csTimeout = await db.find({cs_id: parseInt(data.cs_id)})
          let cstype = 1
          var csinfo = await think.http.get(config.baseUrl + think.global.apilist['/api/csuser/getcsuser'] + '?id=' + data.cs_id)
          
          if (csinfo.data.status === 1) {
            cstype = csinfo.data.cs_info.type
          }
          if (csTimeout.length > 0 && cstype !== 3 && data.type !== 'subscribe') {
            if (csTimeout[0].isinure) {
              console.log('超时设置生效')
              console.log(csTimeout[0].timeout + '毫秒后，开始发送离线回复')
              timeout_list[data.openid] = setTimeout(() => {
                console.log('-------开始发送离线消息')
                let url = think.global.baseUrl + '/Customer_service/outlineMsg'
                console.log(url)
                let datas = {
                  openid: data.openid,
                  butt_id: data.cs_id,
                  fromname: 'client'
                }
                think.http.post(url, datas).then((response) => {
                  console.log(response)
                }).catch((err) => {
                  console.log(err)
                })
              }, csTimeout[0].timeout)
            } else {
              console.log('超时未设置生效')
            }
          } else {
            if (data.type === 'subscribe') {
              console.log('新关注，发送关注')
              let url = think.global.baseUrl + '/Customer_service/outlineMsg'
              let datas = {
                openid: data.openid,
                butt_id: data.cs_id,
                fromname: 'client'
              }
              think.http.post(url, datas).then((response) => {
                console.log(response)
              }).catch((err) => {
                console.log(err)
              })
            }
            if (cstype === 3) {
              console.log('客服已离线，取消超时回复')
            } else {
              console.log('超时未设置')
            }
          }
        } catch (e) {
          console.log(e)
        }
      }

      if ( sendType.length == 0 ) {
        await new loglist({
          level: 'Warn',
          name: '消息发送给客户端',
          type: '服务端',
          result: {
            data: data,
            msg: '当前用户不在线'
          }
        }).save()
        this.json( { status: -1, msg: '当前用户不在线' } );
      } else {
        await new loglist({
          level: 'Info',
          name: '消息发送给客户端',
          type: '服务端',
          result: {
            data: data,
            sendType: sendType
          }
        }).save()
        this.json( { "status": 1, "msg": "发送成功", send_list: sendType } );
      }
    } else {
      console.log('当前客服不在线')
      await new loglist({
        level: 'Warn',
        name: '消息发送给客户端',
        type: '服务端',
        result: {
          data: data,
          msg: '当前用户不在线'
        }
      }).save()
      this.json( { status: -1, msg: '当前客服不在线' } );
    }
    console.log('===========================================')
  }
}